//
//  JCMomentsVC.m
//  PYQDemo
//
//  Created by Guo.JC on 2017/9/2.
//  Copyright © 2017年 coollang. All rights reserved.
//

#import "JCMomentsVC.h"
#import "MJRefresh.h"
#import "JCMomentsModel.h"
#import <CoreLocation/CoreLocation.h>
#import "JCLocation.h"
#import <Qiniu/QiniuSDK.h>
#import "JCMomentsCell.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import "BRPlaceholderTextView.h"
#import <YYKit/YYKit.h>
#import "SQActionSheetView.h"
#import "UIScrollView+YFMJRefresh.h"
#import "MomentsTopicApi.h"
#import "YFFullScreenCameraViewController.h"
#import "YFPostTopicViewController.h"
#import "MyNavigationViewController.h"

@interface JCMomentsVC ()<YYTextViewDelegate,UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,JCMomentsCellDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (nonatomic, strong) NSMutableArray <JCMomentsModel *> *allMomentModel;
@property (nonatomic, strong) CLGeocoder *clGeoCoder;
@property (nonatomic, strong) CLGeocoder *coder2;
@property (weak, nonatomic) IBOutlet UIView *inputView;
@property (weak, nonatomic) IBOutlet YYTextView *inputTextView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputViewBottonConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputViewHeightConstraint;
@property (strong, nonatomic) JCMomentResponseModel *responseModel;
@property (strong, nonatomic) JCMomentsModel *momentModel;
@property (assign, nonatomic) NSInteger pageIndex;
@property (assign, nonatomic) ShowMomentType showMomentType;
@property (strong, nonatomic) UIButton *naviView;
@property (nonatomic, strong) YFSeletePhotoManager *seletePhotoManager;
@property (weak, nonatomic) IBOutlet UIButton *postButton;

@end

@implementation JCMomentsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"圈子";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(postTopicClick:)];
    
    [self initCode];
    [self addNotice];
    [self refreshMomentShowType:ShowMomentTypeAll];///默认全部
    [self configuerTextview];

    
}

- (void)postPureTextTopic {
    if (self.seletePhotoManager != nil) {
        self.seletePhotoManager = nil;
    }
    YFSeletePhotoManager *seleteManager = [[YFSeletePhotoManager alloc] init];
    
    seleteManager.postTopicCallBack = ^(BOOL success) {
        if (success) {
            [self refreshMomentShowType:_showMomentType];
        }
    };
    
    YFPostTopicViewController *topicVc = [[YFPostTopicViewController alloc] init];
    
    topicVc.seletePhotoManager = self.seletePhotoManager;
    MyNavigationViewController *navVc = [[MyNavigationViewController alloc] initWithRootViewController:topicVc];
    topicVc.seletePhotoManager.delegate = topicVc;
    topicVc.isPureText = YES;
    [self presentViewController:navVc animated:YES completion:nil];
}

- (void)postTopicClick:(id)sender {
    [PhotoActionSheetViewController showInParentViewController:self.tabBarController animationType:DetailViewControllerPresentAnimationTypeUp actionBlock:^(kTapActionButtonType btnType) {
        [self gotoSeletePhotoOrTakePhoto:btnType];
    }];
}
- (void)gotoSeletePhotoOrTakePhoto:(kTapActionButtonType)type {
    
    if (self.seletePhotoManager != nil) {
        self.seletePhotoManager = nil;
    }
    YFSeletePhotoManager *seleteManager = [[YFSeletePhotoManager alloc] init];
    
    seleteManager.postTopicCallBack = ^(BOOL success) {
        if (success) {
            [self refreshMomentShowType:_showMomentType];
        }
    };
    self.seletePhotoManager = seleteManager;
    seleteManager.delegate = self;
    [seleteManager showPickerControllerWithType:type targetVc:self];
    
}

- (void)seletePhotoDidFinishPickingPhotos:(NSArray<UIImage *> *)photos assets:(NSArray *)assets isOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        YFPostTopicViewController *topicVc = [[YFPostTopicViewController alloc] init];
        topicVc.seletePhotoManager = self.seletePhotoManager;
        MyNavigationViewController *navVc = [[MyNavigationViewController alloc] initWithRootViewController:topicVc];
        topicVc.seletePhotoManager.delegate = topicVc;
        [self presentViewController:navVc animated:YES completion:nil];
    });
}

/**
 初始化
 */
- (void)initCode{
    __weak typeof(self)weakSelf = self;
    _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf dropRefreshData];
    }];
    _tableview.mj_header.automaticallyChangeAlpha = YES;
    ((MJRefreshNormalHeader *)(_tableview.mj_header)).lastUpdatedTimeLabel.hidden = YES;
    
    _tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadMore];
    }];
    
    _inputTextView.layer.cornerRadius = 5;
    _inputTextView.layer.masksToBounds = YES;
    _inputViewBottonConstraint.constant = - _inputView.bounds.size.height;
    _inputTextView.layer.borderColor = [UIColor colorWithHex:0x999999].CGColor;
    _inputTextView.layer.borderWidth = 0.5;
    
    _naviView = [UIButton buttonWithType:UIButtonTypeCustom];
    _naviView.frame = CGRectMake(0, 0, kYFScreenWidth, 64);
    _naviView.enabled = NO;
    _naviView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0];
    [_naviView addTarget:self action:@selector(cancelAllEdit) forControlEvents:UIControlEventTouchUpInside];
    [[UIApplication sharedApplication].keyWindow addSubview:_naviView];
}

/**
 刷新朋友圈数据
 @param             type            关注、全部
 */
- (void)refreshMomentShowType:(ShowMomentType)type{
    __weak typeof(self)weakSelf = self;
    _showMomentType = type;
    _pageIndex = 1;
    MomentsTopicApi *getTopicListApi = [[MomentsTopicApi alloc] initWithReqType:kGetTopicListApi params:@{@"page":@(_pageIndex).stringValue,@"from":@"0"}];
    
    [[YFNetworkingService sharedInstance] sendRequest:getTopicListApi callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            NSArray *models = [JCMomentsModel creatModelWithArray:getTopicListApi.responseObject[@"errDesc"]];
            weakSelf.allMomentModel = [NSMutableArray arrayWithArray:models];
            [weakSelf.tableview reloadData];
        }
    }];
}

/**
 注册通知
 */
- (void)addNotice{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(popInputView:)
                                                 name:kNoticePopInputView
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(popMenu:)
                                                 name:kNoticePopMenu
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(popDeleteComment:)
                                                 name:kNoticePopDeleteComment
                                               object:nil];
    
}

/**
 删除评论
 */
- (void)popDeleteComment:(NSNotification *)notice{
    __weak typeof(self)weakSelf = self;
    NSDictionary *userInfo = notice.userInfo;
    JCMomentResponseModel *model = userInfo[@"deleteModel"];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"是否删除该条评论？" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *delete = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        if (model.responseID == nil) {
            return;
        }
        MomentsTopicApi *deleteCommentApi = [[MomentsTopicApi alloc] initWithReqType:kDeleteTopicCommentApi params:@{@"responseID":model.responseID}];
        
        [[YFNetworkingService sharedInstance] sendRequest:deleteCommentApi callback:^(BOOL success, id result, NSError *error) {
            if (success) {
                JCMomentsModel *momentModel = model.momentModel;
                [momentModel.responseList removeObject:model];
                ///计算评论所需高度
                [momentModel calculCommetHeight];
                ///计算cell高度
                [momentModel caucalCellHeight];
                [weakSelf.tableview reloadData];
            }else {
                NSLog(@"删除评论失败");
            }
        }];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:delete];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}

/**
 帖子右上角弹出菜单
 */
- (void)popMenu:(NSNotification *)notice{
    __weak typeof(self)weakSelf = self;
    NSDictionary *userInfo = notice.userInfo;
    JCMomentsModel *model = userInfo[@"momentModel"];
    NSIndexPath *indexPath = model.indexPath;
    SQActionSheetView *sheetView = [[SQActionSheetView alloc] initWithTitle:@""
                                                                    buttons:@[@"删除",@"取消"]
                                                                     colors:@[[UIColor redColor],[UIColor blackColor]]
                                                                buttonClick:^(SQActionSheetView *sheetView, NSInteger buttonIndex) {
        if (buttonIndex == 0 && model.topicID != nil) {
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            MomentsTopicApi *deleteTopicApi = [[MomentsTopicApi alloc] initWithReqType:kDeleteTopicApi params:@{@"postID":model.topicID}];
            [[YFNetworkingService sharedInstance] sendRequest:deleteTopicApi callback:^(BOOL success, id result, NSError *error) {
                if (success) {
                    JCMomentsModel *deleteModel;
                    for (JCMomentsModel *dataModel in weakSelf.allMomentModel) {
                        if ([dataModel.topicID isEqualToString:model.topicID]) {
                            deleteModel = dataModel;
                        }
                    }
                    ///删除源数据
                    [weakSelf.allMomentModel removeObject:deleteModel];
                    ///删除cell
                    [weakSelf.tableview deleteRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationRight];
                    [UIView performWithoutAnimation:^{
                        [weakSelf.tableview reloadData];
                    }];
                }
            }];
        }else if (buttonIndex == 1){
        }
    }];
    [sheetView showView];
}

/**
 配置输入框
 */
- (void)configuerTextview {
    _inputTextView.placeholderFont = _inputTextView.font = [UIFont systemFontOfSize:kTextFont];
    _inputTextView.placeholderTextColor = [UIColor colorWithHex:0x999999];
    _inputTextView.textColor = [UIColor blackColor];
    _inputTextView.delegate = self;
    _inputTextView.returnKeyType = UIReturnKeySend;
    self.inputTextView.enablesReturnKeyAutomatically = YES;
    [self updatePostButtonUI];
}

/**
 取消输入控件的响应
 */
- (void)cancelAllEdit{
    _naviView.enabled = NO;
    [_inputTextView resignFirstResponder];
}

//当键盘出现
- (void)keyboardWillShow:(NSNotification *)notification{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height;
    _inputViewBottonConstraint.constant = height - 49;
    [UIView animateWithDuration:.5 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
    _naviView.enabled = YES;
}

//当键退出
- (void)keyboardWillHide:(NSNotification *)notification{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height;
    _inputViewBottonConstraint.constant = - _inputView.bounds.size.height;
    [UIView animateWithDuration:.5 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        [self.view layoutIfNeeded];
//        _inputTextView.text = [NSString stringWithFormat:@"@%@",model.rUserName];
    } completion:^(BOOL finished) {
        
    }];
}

/**
 弹出评论、回复输入
 */
- (void)popInputView:(NSNotification *)notice{
    _responseModel = notice.userInfo[@"model"];
    _momentModel = notice.userInfo[@"commentModel"];
    NSString *placeholder;
    if (_responseModel) {
        placeholder = [NSString stringWithFormat:@"@%@",_responseModel.rUserName];
    }else{
        placeholder = [NSString stringWithFormat:@"@%@",_momentModel.userName];
    }
    _inputTextView.placeholderText = placeholder;
    
    [_inputTextView becomeFirstResponder];
}

- (IBAction)postButtonClick:(UIButton *)sender {
    if (self.inputTextView.text.length > 0) {
        [self.inputTextView resignFirstResponder];
        [self editDone];
    }
}

#pragma mark -- YYTextView代理
- (BOOL)textView:(YYTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if( [@"\n" isEqualToString: text]){
        [textView resignFirstResponder];
        [self editDone];
        return NO;
    }
    return YES;
}

- (void)textViewDidChange:(YYTextView *)textView {
    YYTextLayout *layout = textView.textLayout;
    CGFloat height = MIN(layout.textBoundingSize.height, kAutoHei(80));
    _inputViewHeightConstraint.constant = MAX(18+height, 55);
    [UIView animateWithDuration:0.25 animations:^{
        [self.inputView layoutIfNeeded];
    }];
    [self updatePostButtonUI];
}
- (void)updatePostButtonUI {
    self.postButton.layer.cornerRadius = 4;
    self.postButton.layer.masksToBounds = YES;
    self.postButton.layer.borderWidth = 0.5;
    if (self.inputTextView.text.length > 0 ) {
        self.postButton.layer.borderColor = kSelectedColor.CGColor;
        self.postButton.enabled = YES;
    }else {
        self.postButton.layer.borderColor = [UIColor colorWithHex:0xc8c8c8].CGColor;
        self.postButton.enabled = NO;
    }
}

- (void)editDone{
    __weak typeof(self)weakSelf = self;
    NSString *text = _inputTextView.text;
    NSString *postID;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSLog(@"输入完成:%@",text);
    if (_responseModel) {
        ///回复评论
        MomentsTopicApi *commentApi = [[MomentsTopicApi alloc] initWithReqType:kTopicCommentApi params:@{@"text":text,@"postID":_responseModel.postID,@"parentID":_responseModel.responseID}];
        [[YFNetworkingService sharedInstance] sendRequest:commentApi callback:^(BOOL success, id result, NSError *error) {
            if (success) {
                [hud hideAnimated:YES];
                [weakSelf addNewCommentResponse:commentApi.responseInfo[@"RID"]];
            }else{
                hud.label.text = @"请稍后再试";
                [hud hideAnimated:YES afterDelay:1];
            }
        }];
    }else{
        ///发表评论
        MomentsTopicApi *postCommentApi = [[MomentsTopicApi alloc] initWithReqType:kTopicCommentApi params:@{@"text":text,@"postID":_momentModel.topicID}];
        [[YFNetworkingService sharedInstance] sendRequest:postCommentApi callback:^(BOOL success, id result, NSError *error) {
            if (success) {
                [hud hideAnimated:YES];
                [weakSelf addNewCommentSuccess:postCommentApi.responseInfo[@"RID"]];
            }else{
                hud.label.text = @"请稍后再试";
                
                [hud hideAnimated:YES afterDelay:1];
            }
        }];
    }
}

/**
 新加一条评论
 @params            responseID      服务器返回的评论ID
 */
- (void)addNewCommentSuccess:(NSString *)responseID{
    JCMomentResponseModel *newComment = [JCMomentResponseModel creatNewCommentWithText:_inputTextView.text postID:_momentModel.topicID responseID:responseID];
    [_momentModel addCommentModel:newComment];
    _responseModel = nil;
    _momentModel = nil;
    _inputTextView.text = @"";
    _inputViewHeightConstraint.constant = 35;
    [_tableview reloadData];
}

/**
 新加一条回复
 @params            responseID      服务器返回的回复ID
 */
- (void)addNewCommentResponse:(NSString *)responseID{
    JCMomentResponseModel *newResponse = [JCMomentResponseModel creatNewResponseWithText:_inputTextView.text responseID:responseID commentModel:_responseModel];
    [_responseModel.momentModel addResponseModel:newResponse];
    _responseModel = nil;
    _momentModel = nil;
    _inputTextView.text = @"";
    _inputViewHeightConstraint.constant = 35;
    [_tableview reloadData];
}


/**
 下拉刷新数据
 */
- (void)dropRefreshData{
    __weak typeof(self)weakSelf = self;
    _pageIndex = 1;
    
    MomentsTopicApi *getTopicListApi = [[MomentsTopicApi alloc] initWithReqType:kGetTopicListApi params:@{@"page":@(_pageIndex).stringValue,@"from":@"0"}];
    
    [[YFNetworkingService sharedInstance] sendRequest:getTopicListApi callback:^(BOOL success, id result, NSError *error) {
        [weakSelf.tableview.mj_header endRefreshing];
        if (success) {
            NSArray *models = [JCMomentsModel creatModelWithArray:getTopicListApi.responseObject[@"errDesc"]];
            weakSelf.allMomentModel = [NSMutableArray arrayWithArray:models];
            [weakSelf.tableview reloadData];
        }
    }];

}

/**
 上拉加载更多数据
 */
- (void)loadMore{
    __weak typeof(self)weakSelf = self;
    _pageIndex++;
    MomentsTopicApi *getTopicListApi = [[MomentsTopicApi alloc] initWithReqType:kGetTopicListApi params:@{@"page":@(_pageIndex).stringValue,@"from":@"0"}];
    
    [[YFNetworkingService sharedInstance] sendRequest:getTopicListApi callback:^(BOOL success, id result, NSError *error) {
        [weakSelf.tableview.mj_header endRefreshing];
        if (success) {
            NSArray *models = [JCMomentsModel creatModelWithArray:getTopicListApi.responseObject[@"errDesc"]];
            for (JCMomentsModel *model in models) {
                [weakSelf.allMomentModel addObject:model];
            }
            [weakSelf.tableview reloadData];
            [weakSelf.tableview reloadData];
        }
    }];
}

#pragma mark - tableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _allMomentModel.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JCMomentsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JCMomentsCell" forIndexPath:indexPath];
    JCMomentsModel *model = _allMomentModel[indexPath.row];
    [cell setModel:model indexPath:indexPath delegate:self];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    JCMomentsModel *model = _allMomentModel[indexPath.row];
    return model.showMoreSate == ShowMoreBtnSatePackUp?model.normalCellHeight:model.showMoreCellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [[NSNotificationCenter defaultCenter] postNotificationName:kNoticeCancelAllEdit object:nil];
    return;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
}

#pragma mark - cell代理
/**
 查看更多文字
 */
- (void)watchMoreTextAction:(JCMomentsCell *)cell
                      model:(JCMomentsModel *)model
                  indexPath:(NSIndexPath *)indexPath{
    [UIView performWithoutAnimation:^{
        [self.tableview reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationAutomatic];
    }];
}

/**
 点赞动作
 */
- (void)editLikeAction:(JCMomentsCell *)cell
                 model:(JCMomentsModel *)model
             indexPath:(NSIndexPath *)indexPath{
    [UIView performWithoutAnimation:^{
        [self.tableview reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationAutomatic];
    }];
}

#pragma mark - scrollview代理
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    _naviView.enabled = NO;
    [[NSNotificationCenter defaultCenter] postNotificationName:kNoticeCancelAllEdit object:nil];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



@end
